﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using FapCore.Listeners;
using System.Linq;
using FAP.DataAccess;
using FAP.DataAccess.BLL;
using FapCore.Forms;
using Fiddler;

namespace FapCore
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1301:AvoidDuplicateAccelerators")]
     partial class MainForm : Form, PostingDataListener
    {
        public List<chitietbuocthuchien> fields = new List<chitietbuocthuchien>();
        HtmlElement element = null;
        StyleGenerator sg = new StyleGenerator();
        //List<buocthuchien> bths;
        List<website> dsWebsite;
        List<chitietnghiepvu> ctnvs;
        int pageIndex = 1;
        int step = 1;
        public static taikhoan tk = null;
        public int iNghiepVu = 1;
        //cbbNghiepVu.SelectedIndex + 1

        public MainForm()
        {
            InitializeComponent();

            _windowManager = new WindowManager(this.tabControl, this);
            _windowManager.CommandStateChanged += new EventHandler<CommandStateEventArgs>(_windowManager_CommandStateChanged);
            _windowManager.StatusTextChanged += new EventHandler<TextChangedEventArgs>(_windowManager_StatusTextChanged);
            frmChooseWork frmChoose = new frmChooseWork();
            frmChoose.ShowDialog();
            cbbNghiepVu.SelectedIndex = frmChoose.m_iSelected;

            Fiddler.FiddlerApplication.OnNotification += delegate(object sender, NotificationEventArgs oNEA) { Console.WriteLine("** NotifyUser: " + oNEA.NotifyString); };
            Fiddler.FiddlerApplication.Log.OnLogString += delegate(object sender, LogEventArgs oLEA) { Console.WriteLine("** LogString: " + oLEA.LogString); };

            Fiddler.FiddlerApplication.BeforeRequest += delegate(Fiddler.Session oS)
            {

                //Console.WriteLine("Before request for:\t" + oS.fullUrl);
                if (oS.RequestMethod == "POST")
                {
                    var data = oS.RequestBody;
                    if (data != null)//when it's a post package
                    {
                        string s = Encoding.UTF8.GetString(data, 0, data.Length);
                        fields = Converter.ConvertStringToField(s);
                        onPostingData(fields, oS.fullUrl, iNghiepVu);
                        fields = null;
                    }
                }
                // In order to enable response tampering, buffering mode must
                // be enabled; this allows FiddlerCore to permit modification of
                // the response in the BeforeResponse handler rather than streaming
                // the response to the client as the response comes in.
                oS.bBufferResponse = true;
            };


            // For the purposes of this demo, we'll forbid connections to HTTPS 
            // sites that use invalid certificates
            Fiddler.CONFIG.IgnoreServerCertErrors = false;

            // Because we've chosen to decrypt HTTPS traffic, makecert.exe must
            // be present in the Application folder.
            Fiddler.FiddlerApplication.Startup(8877, true, true);

        }

        // Update the status text
        void _windowManager_StatusTextChanged(object sender, TextChangedEventArgs e)
        {
            this.toolStripStatusLabel.Text = e.Text;
        }

        // Enable / disable buttons
        void _windowManager_CommandStateChanged(object sender, CommandStateEventArgs e)
        {
            this.forwardToolStripButton.Enabled = ((e.BrowserCommands & BrowserCommands.Forward) == BrowserCommands.Forward);
            this.backToolStripButton.Enabled = ((e.BrowserCommands & BrowserCommands.Back) == BrowserCommands.Back);
            // this.printPreviewToolStripButton.Enabled = ((e.BrowserCommands & BrowserCommands.PrintPreview) == BrowserCommands.PrintPreview);
            this.printPreviewToolStripMenuItem.Enabled = ((e.BrowserCommands & BrowserCommands.PrintPreview) == BrowserCommands.PrintPreview);
            //this.printToolStripButton.Enabled = ((e.BrowserCommands & BrowserCommands.Print) == BrowserCommands.Print);
            this.printToolStripMenuItem.Enabled = ((e.BrowserCommands & BrowserCommands.Print) == BrowserCommands.Print);
            //this.homeToolStripButton.Enabled = ((e.BrowserCommands & BrowserCommands.Home) == BrowserCommands.Home);
            //this.searchToolStripButton.Enabled = ((e.BrowserCommands & BrowserCommands.Search) == BrowserCommands.Search);
            this.refreshToolStripButton.Enabled = ((e.BrowserCommands & BrowserCommands.Reload) == BrowserCommands.Reload);
            this.stopToolStripButton.Enabled = ((e.BrowserCommands & BrowserCommands.Stop) == BrowserCommands.Stop);
        }

        #region Tools menu
        // Executed when the user clicks on Tools -> Options
        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (OptionsForm of = new OptionsForm())
            {
                of.ShowDialog(this);
            }
        }
        // Tools -> Show script errors
        private void scriptErrorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //ScriptErrorManager.Instance.ShowWindow();
        }

        #endregion

        #region File Menu

        // File -> Print
        private void printToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Print();
        }

        // File -> Print Preview
        private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintPreview();
        }

        // File -> Exit
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        // File -> Open URL
        ExtendedWebBrowser brw;
        private void openUrlToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (OpenUrlForm ouf = new OpenUrlForm())
            {
                if (ouf.ShowDialog() == DialogResult.OK)
                {
                    brw = _windowManager.New(false);
                    brw.setListener(this);
                    brw.Navigate(ouf.Url);

                }
            }
        }
        private void saveCaptcha()
        {
            List<string> path = new List<string>();

            Console.WriteLine(element.InnerText);

            MessageBox.Show(element.InnerText);

            while (!element.TagName.Equals("HTML"))// con tag cha
            {
                HtmlElement parent = element.Parent;//tag cha

                string tagName = element.TagName;// vi du tag DIV

                int position = 1;// vi tri cua tag con can tim trong tag cha

                foreach (HtmlElement elem in parent.Children)// duyet tag con
                {
                    if (elem.TagName.Equals(tagName))// cung loai tag con tim
                    {
                        if (elem.GetHashCode() != element.GetHashCode())
                        {
                            position++;
                        }
                        else
                        {
                            string curPath = tagName;

                            if (position != 1)// loai tag nay duy nhat
                            {
                                curPath += "[" + position + "]";
                            }

                            path.Add(curPath);

                            break;

                        }
                    }
                }
                element = parent;
            }



        }

        void Body_MouseDown(object sender, HtmlElementEventArgs e)
        {
            saveCaptcha();
        }

        void Body_MouseUp(object sender, HtmlElementEventArgs e)
        {
            element = brw.Document.GetElementFromPoint(e.MousePosition);
            resetElement(element);
        }

        private void resetElement(HtmlElement element)
        {
            sg.Clear();
            sg.SetStyle("color", "#999999");
            element.Style = sg.GetStyleString();
        }


        // File -> Open File
        private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Filter = FAP.LearningMachine.Properties.Resources.OpenFileDialogFilter;
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    Uri url = new Uri(ofd.FileName);
                    WindowManager.Open(url);
                }
            }
        }
        #endregion

        #region Help Menu

        // Executed when the user clicks on Help -> About
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About();
        }

        /// <summary>
        /// Shows the AboutForm
        /// </summary>
        private void About()
        {
            using (AboutForm af = new AboutForm())
            {
                af.ShowDialog(this);
            }
        }

        #endregion


        /// <summary>
        /// The WindowManager class
        /// </summary>
        public WindowManager _windowManager;

        // This is handy when all the tabs are closed.
        private void tabControl_VisibleChanged(object sender, EventArgs e)
        {
            if (tabControl.Visible)
            {
                this.panel1.BackColor = SystemColors.Control;
            }
            else
                this.panel1.BackColor = SystemColors.AppWorkspace;
        }

        // Starting the app here...
        private void MainForm_Load(object sender, EventArgs e)
        {

            // Open a new browser window
            this.WindowState = FormWindowState.Maximized;
            cbbNghiepVu.DropDownStyle = ComboBoxStyle.DropDownList;
            TTCBBMethod.DropDownStyle = ComboBoxStyle.DropDownList;
            TTCBBMethod.SelectedIndex = 0;
            _windowManager.New();
            LoadRegisterPages();
            //this._windowManager.ActiveBrowser.Navigate("google.com");
            //if (bths.Count > 0)
            //{
            //    this.address.Text = bths[1].link;
            //}

        }
        DataHelper helper;
        private void LoadRegisterPages()
        {
            helper = new DataHelper();
            //            bths = new List<buocthuchien>();
            dsWebsite = new List<website>();
            ctnvs = helper.GetAllChiTietNghiepVu();
            //bths = helper.GetAllValidBuocThucHien();
            dsWebsite = helper.Laywebsite();
            //lbCurrentPage.Text = bths[0].id.ToString();
            //foreach (chitietnghiepvu ctnv in ctnvs)
            //{
            //    if (ctnv.nghiepvu.id == 1)
            //    {
            //        buocthuchien bth = helper.getByNghiepVuId(ctnv.id);
            //        bths.Add(bth);
            //    }
            //}     
            btnUpdate.Text = "Step " + step;
        }

        //used to navigate to  a specified page
        private void navigate(string address)
        {


            if (MainForm.tk == null)
            {
            }
            else
            {
                if (DialogResult.Yes == MessageBox.Show("Save user?", "Save user?", MessageBoxButtons.YesNo))
                {
                    btnPostManual_Click(null, null);
                    MainForm.tk = null;
                }
                else
                {
                    MainForm.tk = null;
                }
                
            }
            this._windowManager.ActiveBrowser.Navigate(address);
            m_address = address;
            KiemTraChiTietNghiepVu(address);
            step = 1;
            btnUpdate.Text = "Step " + step;
        }

        #region Printing & Print Preview
        private void Print()
        {
            ExtendedWebBrowser brw = _windowManager.ActiveBrowser;
            if (brw != null)
                brw.ShowPrintDialog();
        }

        private void PrintPreview()
        {
            ExtendedWebBrowser brw = _windowManager.ActiveBrowser;
            if (brw != null)
                brw.ShowPrintPreviewDialog();
        }
        #endregion

        #region Toolstrip buttons
        private void closeWindowToolStripButton_Click(object sender, EventArgs e)
        {
            this._windowManager.New();
        }

        private void closeToolStripButton_Click(object sender, EventArgs e)
        {
            this._windowManager.Close();
        }

        private void printToolStripButton_Click(object sender, EventArgs e)
        {
            Print();
        }

        private void printPreviewToolStripButton_Click(object sender, EventArgs e)
        {
            PrintPreview();
        }

        private void backToolStripButton_Click(object sender, EventArgs e)
        {
            if (_windowManager.ActiveBrowser != null && _windowManager.ActiveBrowser.CanGoBack)
                _windowManager.ActiveBrowser.GoBack();
        }

        private void forwardToolStripButton_Click(object sender, EventArgs e)
        {
            if (_windowManager.ActiveBrowser != null && _windowManager.ActiveBrowser.CanGoForward)
                _windowManager.ActiveBrowser.GoForward();
        }

        private void stopToolStripButton_Click(object sender, EventArgs e)
        {
            if (_windowManager.ActiveBrowser != null)
            {
                _windowManager.ActiveBrowser.Stop();
            }
            stopToolStripButton.Enabled = false;
        }

        private void refreshToolStripButton_Click(object sender, EventArgs e)
        {
            if (_windowManager.ActiveBrowser != null)
            {
                _windowManager.ActiveBrowser.Refresh(WebBrowserRefreshOption.Normal);
            }
        }

        private void homeToolStripButton_Click(object sender, EventArgs e)
        {
            if (_windowManager.ActiveBrowser != null)
                _windowManager.ActiveBrowser.GoHome();
        }

        private void searchToolStripButton_Click(object sender, EventArgs e)
        {
            if (_windowManager.ActiveBrowser != null)
                _windowManager.ActiveBrowser.GoSearch();
        }

        #endregion



        public WindowManager WindowManager
        {
            get { return _windowManager; }
        }
        //
        public void onPostingData(List<chitietbuocthuchien> iFields,string strLink,int iNghiepVu)
        {
            buocthuchien bth = new buocthuchien();
            bth.link = strLink;
            bth.method = "POST";
            bth.trangthai = 1;

            website wTEmp = dsWebsite.Where(m => m.link == m_address).SingleOrDefault();
            if (wTEmp != null)
            {
                var chiTietNghiepVu = helper.GetChiTietNghiepVu(wTEmp.id, iNghiepVu);
                if (chiTietNghiepVu != null)
                {
                    //m_log.Debug(string.Format("Tạo bước thực hiện {0}, chi tiết nghiệp vụ {1}", bth.thutu, chiTietNghiepVu.id));
                    //insert
                    bth.chitietnghiepvuid = chiTietNghiepVu.id;
                    bth.thutu = step;


                    btnUpdate.Text = "Step " + step;
                }
            }

            //fields.AddRange(iFields);
            DataShowingForm form = new DataShowingForm(fields, bth);
            form.Link = strLink;
            if (DialogResult.OK == form.ShowDialog())
            {
                step++;
            }

            iFields = new List<chitietbuocthuchien>();
            fields = new List<chitietbuocthuchien>();

        }


        public void onPostingData(List<chitietbuocthuchien> iFields)
        {
            return ;
            /////////////////////////////////////////////////////////////////////////////////////
            buocthuchien bth = new buocthuchien();
            bth.link = this._windowManager.ActiveBrowser.Url.AbsoluteUri;
            bth.method = "POST";
            bth.trangthai = 1;

            website wTEmp = dsWebsite.Where(m => m.link == m_address).SingleOrDefault();
            if (wTEmp != null)
            {
                var chiTietNghiepVu = helper.GetChiTietNghiepVu(wTEmp.id, cbbNghiepVu.SelectedIndex + 1);
                if (chiTietNghiepVu != null)
                {
                    //m_log.Debug(string.Format("Tạo bước thực hiện {0}, chi tiết nghiệp vụ {1}", bth.thutu, chiTietNghiepVu.id));
                    //insert
                    bth.chitietnghiepvuid = chiTietNghiepVu.id;
                    bth.thutu = step;

                    
                    btnUpdate.Text = "Step " + step;
                }
            }

            fields.AddRange(iFields);
            DataShowingForm form = new DataShowingForm(fields, bth);
            if (DialogResult.OK == form.ShowDialog())
            {
                step++;
            }
            
            iFields = new List<chitietbuocthuchien>();
            fields = new List<chitietbuocthuchien>();

        }



        public void onCaptchaClicked(string path, string text)
        {
            /*
            if (ttCbCaptcha.DisplayStyle == ToolStripItemDisplayStyle.Image)
            {
                chitietbuocthuchien captchaDiv = new chitietbuocthuchien();
                captchaDiv.tenfield = "captchadiv";
                captchaDiv.dulieumacdinh = path;
                if (fields.Count == 0)
                {

                    fields.Add(captchaDiv);
                }
                else
                {
                    fields[0] = captchaDiv;
                }
                //MessageBox.Show(text);
            }
            */
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (ttCbCaptcha.DisplayStyle == ToolStripItemDisplayStyle.Image)
            {
                ttCbCaptcha.DisplayStyle = ToolStripItemDisplayStyle.Text;
            }
            else
            {
                ttCbCaptcha.DisplayStyle = ToolStripItemDisplayStyle.Image;
            }
        }

        private void btnNavigate_Click(object sender, EventArgs e)
        {
                navigate(address.Text);
        }

        private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void btnNextPage_Click(object sender, EventArgs e)
        {
            pageIndex++;
            //buocthuchien bth = bths[pageIndex];            
            website bth = dsWebsite[pageIndex];
            //lbCurrentPage.Text = bth.id.ToString();
            this.address.Text = bth.link;
        }

        private void KiemTraChiTietNghiepVu(string _address)
        {
            if (_address == null)
                return;
            iNghiepVu = 0;
            switch (cbbNghiepVu.SelectedIndex)
            { 
                case 0: //đăng kí
                    iNghiepVu = 1;
                    break;
                case 1: //đăng nhập
                    iNghiepVu = 2;
                    break;
                case 2: //đăng tin
                    iNghiepVu = 3;
                    break;
                case 3: //up tin
                    iNghiepVu = 4;
                    break;
            }
            //m_log.Info(string.Format("Kiểm tra chiết tiết nghiệp vụ {0} : website {1}", cbbNghiepVu.SelectedText, _address));
            website wTEmp = dsWebsite.Where(m =>_address.IndexOf(m.link)>-1).SingleOrDefault();
            if(wTEmp!=null)
            {
                var nghiepVu = helper.GetChiTietNghiepVu(wTEmp.id, iNghiepVu);
                if (nghiepVu == null)
                {
                    //m_log.Debug(string.Format("Tạo chi tiết nghiệp vụ {0} : website {1}", cbbNghiepVu.SelectedText, _address));
                    //insert
                    chitietnghiepvu c=new chitietnghiepvu();
                    c.nghiepvuid = iNghiepVu;
                    c.trangthai=1;
                    c.websiteid = wTEmp.id;
                    if (helper.ThemNghiepVu(c))
                    {
                        //m_log.Info(string.Format("Tạo chi tiết nghiệp vụ {0} : website {1} thành công", cbbNghiepVu.SelectedText, _address));
                    }
                    else
                    {
                        //m_log.Error(string.Format("Tạo chi tiết nghiệp vụ {0} : website {1} thất bại", cbbNghiepVu.SelectedText, _address));
                    }
                }
            }
        }

        int i = 0;
        private string m_address;
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == MessageBox.Show("Save step " + step + " ?", "", MessageBoxButtons.OKCancel))
            {
                //m_log.Info("Lưu link get stetp " + step);

                buocthuchien bth = new buocthuchien();
                bth.link = this._windowManager.ActiveBrowser.Url.AbsoluteUri;
                bth.method = "GET";
                bth.trangthai = 1;
                //bth.thutu = TTCbbStep.SelectedIndex + 1;
                bth.thutu = step;
                //bth.chitietnghiepvuid = ctnvs[pageIndex].id;

                website wTEmp = dsWebsite.Where(m => m.link == m_address).SingleOrDefault();
                if (wTEmp != null)
                {
                    var chiTietNghiepVu = helper.GetChiTietNghiepVu(wTEmp.id, cbbNghiepVu.SelectedIndex + 1);
                    if (chiTietNghiepVu != null)
                    {
                        //m_log.Debug(string.Format("Tạo bước thực hiện {0}, chi tiết nghiệp vụ {1}", bth.thutu, chiTietNghiepVu.id));
                        //insert
                        bth.chitietnghiepvuid = chiTietNghiepVu.id;
                        ChangeLink frmChangeLink = new ChangeLink();
                        frmChangeLink.Link = bth.link;
                        if (DialogResult.OK == frmChangeLink.ShowDialog())
                        {
                            bth.link = frmChangeLink.Link;
                        }
                        helper.ThemBuocThucHien(bth);
                        step++;
                        btnUpdate.Text = "Step " + step;
                    }
                }
            }
        }

        private void btnGoto_Click(object sender, EventArgs e)
        {
            pageIndex = Convert.ToInt32(txtgoto.Text.ToString());
            address.Text = dsWebsite[pageIndex].link;
        }

        private void btnPostManual_Click(object sender, EventArgs e)
        {
            PostManual p = new PostManual();
            p.mfrmMain = this;
            p.ShowDialog();
            //helper.ThemTaiKhoan(MainForm.tk);
            //MainForm.tk = null;
            //MessageBox.Show("Save OK");
        }

        private void cbbNghiepVu_SelectedIndexChanged(object sender, EventArgs e)
        {
            KiemTraChiTietNghiepVu(m_address);
        }

        private void btnKetQua_Click(object sender, EventArgs e)
        {
            //goi ham luu ket qua
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Fiddler.FiddlerApplication.Shutdown();
        }
    }
}